package com.wen.edu.controller;


import com.wen.commonutils.ResultEntity;
import com.wen.edu.api.VodApi;
import com.wen.edu.entity.EduVideo;
import com.wen.edu.service.EduVideoService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author wen
 * @since 2021-05-29
 */
@RestController
@RequestMapping("/edu/service/video")
public class EduVideoController {
    @Resource
    private EduVideoService eduVideoService;
    //    注入VodApi为了实现删除小节就能删除对应的视频
    @Resource
    private VodApi vodApi;

    /**
     * 查询课程小结
     *
     * @param videoId target id
     * @return result of operation
     */
    @GetMapping("getVideo/{videoId}")
    public ResultEntity getVideo(@PathVariable("videoId") String videoId) {
        EduVideo video = eduVideoService.getById(videoId);
        return ResultEntity.ok().data("video", video);
    }


    /**
     * 添加课程小结
     *
     * @param eduVideo target
     * @return result of operation
     */
    @PostMapping("addVideo")
    public ResultEntity addVideo(@RequestBody EduVideo eduVideo) {
        eduVideoService.save(eduVideo);
        return ResultEntity.ok();
    }

    /**
     * 修改课程小结
     *
     * @param eduVideo target
     * @return result of operation
     */
    @PostMapping("updateVideo")
    public ResultEntity updateVideo(@RequestBody EduVideo eduVideo) {
        eduVideoService.updateById(eduVideo);
        return ResultEntity.ok();
    }

    /**
     * 删除课程小结
     *
     * @param videoId target
     * @return result of operation
     */
    @DeleteMapping("deleteVideo/{videoId}")
    public ResultEntity deleteVideo(@PathVariable("videoId") String videoId) {
//        删除视频,需要根据小节id得到对应的视频id,然后才调用删除视频方法
        EduVideo eduVideo = eduVideoService.getById(videoId);
        String videoSourceId = eduVideo.getVideoSourceId();
//        如果小节存在相应的视频,才调用删除方法
        if (!StringUtils.isEmpty(videoSourceId))
//        根据视频id,实现远程调用删除视频
            vodApi.deleteSingleAlyVideo(videoSourceId);
//      必须先删除视频然后再删除小节,否则先删除小节,就不存在对应的小节id,也就拿不到对应的视频id,也就删除不了存储在阿里云上的视频
        eduVideoService.removeById(videoId);
        return ResultEntity.ok();
    }
}

